from decimal import Decimal

import akshare as ak
from datetime import datetime

from akshare_analysis.ak_code_config import read_futures_config
from future_history_app.models import FuturesCurrent
import logging

# 获取自定义日志器（与 settings.py 中的 'app' 对应）
logger = logging.getLogger('app')

def fetch_futures_current_data(ak_code_configs, current_date=None):
    """获取指定合约指定日期的行情数据"""

    # 如果未指定当前日期，使用今天
    if current_date is None:
        current_date = datetime.now().strftime("%Y%m%d")
    # 转换为datetime对象以便进行日期运算
    current_date_obj = datetime.strptime(current_date, "%Y%m%d")

    # 格式化当前要查询的日期
    date_str = current_date_obj.strftime("%Y%m%d")

    # 构建所有合约代码的字符串
    all_symbols = ','.join([config.ak_code for config in ak_code_configs])

    df = ak.futures_zh_spot(symbol=all_symbols, market="CF", adjust="0")
    if df is not None and not df.empty:
        # 遍历返回的每一行数据
        for index, row in df.iterrows():
            current = convert_to_decimal(row.get('current_price', None))

            hold = row.get('hold', None)

            symbol = row.get('symbol', '').rstrip('连续')

            each_config_db = next((c for c in ak_code_configs if c.breed == symbol), None)
            if each_config_db is None:
                continue
            # 使用 update_or_create，返回 (obj, created)
            obj, created = FuturesCurrent.objects.update_or_create(
                ak_code=each_config_db.ak_code,
                defaults={
                    "code": each_config_db.code,
                    "code_complete": each_config_db.code_complete,
                    "breed": each_config_db.breed,
                    "exchange": each_config_db.exchange,
                    "hold":int(hold),
                    'current': current,
                    'trans_date': int(date_str),
                }
            )

            # 如果不是新建的记录（即已有数据），才计算 current_to_lowest
            if not created and obj.minimum is not None and obj.minimum != 0:
                current_decimal = Decimal(str(current)) if current is not None else Decimal('0')
                obj.current_to_lowest = current_decimal / obj.minimum
                obj.save()
                logger.info(f"更新了 {each_config_db.ak_code} 的 current_to_lowest: {obj.current_to_lowest}")


# 数据类型转换函数
def convert_to_decimal(value):
    if value is None or value == '' or value == 'None':
        return None
    try:
        # 处理可能包含逗号的数字（如 "5,019"）
        if isinstance(value, str):
            value = value.replace(',', '')
        return float(value)
    except (ValueError, TypeError):
        logger.info(f"无法转换值 {value} 为数值类型")
        return None


if __name__ == '__main__':
    # 测试读取配置
    ak_code_data = read_futures_config()
    fetch_futures_current_data(ak_code_data)
    # for row in ak_code_data:
    #     logger.info(row.ak_code, row.exchange, row.breed, row.code, row.code_complete)
    #     # 示例：获取玻璃主力合约数据
    #     # contract_code = "V0"  # 玻璃主力合约代码
    #     #
    #     # # 可以指定起始日期，如 "20250630"，也可以留空使用今天
    #     fetch_futures_current_data(row)
